/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.broker.loadbalance;

import java.util.concurrent.ConcurrentHashMap;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.broker.BrokerPathConfigHelper;
import org.apache.rocketmq.common.ConfigManager;
import org.apache.rocketmq.remoting.protocol.RemotingSerializable;
import org.apache.rocketmq.remoting.protocol.body.SetMessageRequestModeRequestBody;

public class MessageRequestModeManager extends ConfigManager {

    /**
     * broker控制器
     */
    private transient BrokerController brokerController;

    /**
     * key是主题名称
     * value是一个map，key是消费者组名称，value是设置消息请求模式请求体
     */
    private ConcurrentHashMap<String/*topic*/, ConcurrentHashMap<String/*consumerGroup*/, SetMessageRequestModeRequestBody>>
        messageRequestModeMap = new ConcurrentHashMap<>();

    public MessageRequestModeManager() {
        // empty construct for decode
    }

    public MessageRequestModeManager(BrokerController brokerController) {
        this.brokerController = brokerController;
    }

    /**
     * 设置消息请求模式
     * @param topic           主题名称
     * @param consumerGroup   消费组名称
     * @param requestBody     请求报文体
     */
    public void setMessageRequestMode(String topic, String consumerGroup, SetMessageRequestModeRequestBody requestBody) {
        // 从消息请求模式表中获取指定主题的消费组请求模式map集合
        // 一个主题可以有多个消费组，每个消费组有自己的设置消息请求模式报文体
        ConcurrentHashMap<String, SetMessageRequestModeRequestBody> consumerGroup2ModeMap = messageRequestModeMap.get(topic);
        // 如果没有找到
        if (consumerGroup2ModeMap == null) {
            // 新建map集合，key是消费组名称，value是设置消息请求模式报文体
            consumerGroup2ModeMap = new ConcurrentHashMap<>();
            // 将主题名称，map集合键值对放到消息请求模式表中
            ConcurrentHashMap<String, SetMessageRequestModeRequestBody> pre =
                messageRequestModeMap.putIfAbsent(topic, consumerGroup2ModeMap);
            // 如果pre不是null，表示有其他线程请求在该线程之前将键值对放进去了，本次put失败
            if (pre != null) {
                // 获取pre作为当前的map
                consumerGroup2ModeMap = pre;
            }
        }
        // 在map集合中放入当前消费组名称和请求报文体的键值对
        consumerGroup2ModeMap.put(consumerGroup, requestBody);
    }

    /**
     * 根据主题名称，消费组名称获取设置消息请求模式报文体
     * @param topic          主题名称
     * @param consumerGroup  消费组名称
     * @return 设置消息请求模式报文体对象
     */
    public SetMessageRequestModeRequestBody getMessageRequestMode(String topic, String consumerGroup) {
        ConcurrentHashMap<String, SetMessageRequestModeRequestBody> consumerGroup2ModeMap = messageRequestModeMap.get(topic);
        if (consumerGroup2ModeMap != null) {
            return consumerGroup2ModeMap.get(consumerGroup);
        }

        return null;
    }

    public ConcurrentHashMap<String, ConcurrentHashMap<String, SetMessageRequestModeRequestBody>> getMessageRequestModeMap() {
        return this.messageRequestModeMap;
    }

    public void setMessageRequestModeMap(ConcurrentHashMap<String, ConcurrentHashMap<String, SetMessageRequestModeRequestBody>> messageRequestModeMap) {
        this.messageRequestModeMap = messageRequestModeMap;
    }

    /**
     * 将当前对象编码为json字符串并返回
     * @return
     */
    @Override
    public String encode() {
        return this.encode(false);
    }

    /**
     * 获取配置文件路径
     * @return
     */
    @Override
    public String configFilePath() {
        // 日志数据存储的目录： 默认是：${user.home}/store 可以通过 -Drocketmq.store.path=xxx 指定
        // ${user.home}/store/config/messageRequestMode.json
        return BrokerPathConfigHelper.getMessageRequestModePath(this.brokerController.getMessageStoreConfig().getStorePathRootDir());
    }

    /**
     * 将json字符串解码为消息请求模式管理器对象，获取其中的消息请求模式表，并赋值给当前对象的messageRequestModeMap
     * @param jsonString
     */
    @Override
    public void decode(String jsonString) {
        if (jsonString != null) {
            MessageRequestModeManager obj = RemotingSerializable.fromJson(jsonString, MessageRequestModeManager.class);
            if (obj != null) {
                this.messageRequestModeMap = obj.messageRequestModeMap;
            }
        }
    }

    /**
     * 将当前对象编码为json字符串，并返回
     * @param prettyFormat
     * @return
     */
    @Override
    public String encode(boolean prettyFormat) {
        return RemotingSerializable.toJson(this, prettyFormat);
    }
}
